using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Linq;
using System.IO;
using Microsoft.SharePoint.WebPartPages;
using System.Drawing;

using Microsoft.SharePoint.WebControls;
using Adartse.Sharepoint.WebPartCode;
using Adartse.Sharepoint.Interfaces;
using Adartse.Sharepoint.WebPartEditors;

namespace Adartse.Sharepoint
{
    [Guid("b6762a87-3e58-4bf0-ae5c-9b8991afb868")]
    public class AWPListRepeater : AWPBase, IWebEditable, IHideableWebPart, IShowableWebPart
    {
        public string ListName { get; set; }
        public string HtmlContent { get; set; }
        public string ContainterID { get; set; }
        public string ContainerClass { get; set; }
        public bool IsIDEnabled { get; set; }
        public bool IsClassEnabled { get; set; }
        public int ContainerType { get; set; }
        public string HeaderContent { get; set; }
        //new
        public bool IsByView { get; set; }
        public string ViewName { get; set; }

        public string EmptyTemplate { get; set; }

        internal Dictionary<string, string> FieldList { get; set; }

        public string ListFieldsText
        {
            get { return Utilities.JSONSerializer<Dictionary<string, string>>(FieldList); }
            set { FieldList = Utilities.JSONDeserializer<Dictionary<string, string>>(value); }
        }

        public AWPListRepeater()
        {
            this.ExportMode = WebPartExportMode.All;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string template = this.HtmlContent;

                //HideMe Validation
                if (this.EnableHide && SPContext.Current.FormContext.FormMode != SPControlMode.Edit)
                {
                    if (!string.IsNullOrEmpty(this.HideQueryStringParameter) &&
                        this.Page.Request.QueryString.HasKeys() &&
                        this.Page.Request.QueryString[this.HideQueryStringParameter].Equals(this.HideQueryStringParameterValue))
                    {
                        this.Visible = false;
                        return;
                    }
                }

                //ShowMe Validation
                if (this.EnableShow && SPContext.Current.FormContext.FormMode != SPControlMode.Edit)
                {
                    if (string.IsNullOrEmpty(this.ShowQueryStringParameter) ||
                        !this.Page.Request.QueryString.HasKeys() ||
                        !this.Page.Request.QueryString[this.ShowQueryStringParameter].Equals(this.ShowQueryStringParameterValue))
                    {
                        this.Visible = false;
                        return;
                    }
                }

                #region Opening Container Type
                if (IsIDEnabled)
                    writer.AddAttribute(HtmlTextWriterAttribute.Id, ContainterID);
                if (IsClassEnabled)
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, ContainerClass);

                switch (ContainerType)
                {
                    case 0:
                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                        break;
                    case 1:
                        writer.RenderBeginTag(HtmlTextWriterTag.Table);
                        break;
                    case 2:
                        writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                        break;
                    default:
                        break;
                }
                #endregion

                #region Header Container
                if (!string.IsNullOrEmpty(HeaderContent))
                {
                    switch (ContainerType)
                    {
                        case 0:
                            writer.AddAttribute(HtmlTextWriterAttribute.Class, "header");
                            writer.RenderBeginTag(HtmlTextWriterTag.Div);
                            break;
                        case 1:
                            writer.RenderBeginTag(HtmlTextWriterTag.Th);
                            break;
                        case 2:
                            writer.RenderBeginTag(HtmlTextWriterTag.H3);
                            break;
                        default:
                            break;
                    }
                    writer.WriteLine(HeaderContent);
                    writer.RenderEndTag();
                }

                #endregion

                if (!string.IsNullOrEmpty(ListName))
                {
                    SPList list = SPContext.Current.Web.Lists.GetList(new Guid(this.ListName), false); ;

                    if (list != null)
                    {
                        #region Gettin' List Items
                        SPListItemCollection items = null;
                        SPView view = null;
                        if (IsByView)
                            view = list.GetView(new Guid(ViewName));
                        else
                            view = list.DefaultView;

                        SPQuery query = new SPQuery(view);
                        query.ViewFields = "<FieldRef Name=\"ID\"/>";

                        items = list.GetItems(query);
                        #endregion

                        #region Main Foreach
                        if (items.Count > 0)
                        {
                            foreach (SPListItem item in items)
                            {
                                //Filling and Replacing Template
                                sb.Remove(0, sb.Length);
                                sb.Append(template);
                                SPListItem superItem = SPContext.Current.Web.GetListItem(item.Url);
                                foreach (var key in FieldList)
                                {
                                    if (list.Fields.GetFieldByInternalName(key.Value).Type == SPFieldType.Calculated)
                                        sb.Replace(key.Key, superItem.GetFormattedValue(key.Value));
                                    else
                                        sb.Replace(key.Key, Convert.ToString(superItem[key.Value]));
                                }
                                //--

                                switch (ContainerType)
                                {
                                    case 0:
                                        writer.RenderBeginTag(HtmlTextWriterTag.Div);
                                        break;
                                    case 1:
                                        writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                                        break;
                                    case 2:
                                        writer.RenderBeginTag(HtmlTextWriterTag.Li);
                                        break;
                                    default:
                                        break;
                                }

                                writer.WriteLine(sb.ToString());

                                writer.RenderEndTag();
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(EmptyTemplate))
                            {
                                writer.AddStyleAttribute(HtmlTextWriterStyle.Color, "red");
                                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                                writer.WriteEncodedText("No item to display");
                                writer.RenderEndTag();

                            }
                            else
                                writer.Write(EmptyTemplate);
                        }
                        #endregion

                    }
                }
                else
                {
                    writer.WriteEncodedText("No list assigned");
                }
                //Closing Container
                writer.RenderEndTag();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }

        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();
            editors.Add(new ListRepeaterEditor() { ID = this.ID + "_CustomListContentEditor" });
            editors.Add(new HideWebPartEditor() { ID = this.ID + "_HideMeEditor" });
            editors.Add(new ShowWebPartEditor() { ID = this.ID + "_ShowMeEditor" });
            EditorPartCollection baseEditors = base.CreateEditorParts();
            return new EditorPartCollection(baseEditors, editors);
        }

        #region IHideableWebPart Members

        public bool EnableHide { get; set; }

        public string HideQueryStringParameter { get; set; }

        public string HideQueryStringParameterValue { get; set; }

        #endregion

        #region IShowableWebPart Members

        public bool EnableShow { get; set; }

        public string ShowQueryStringParameter { get; set; }

        public string ShowQueryStringParameterValue { get; set; }

        #endregion
    }
}
